package cn.lds.j367.dsbank.entity;

import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.*;

@Data
public class Employee extends BaseEntity implements UserDetails {

    private Integer empId;
    @NotNull(message = "姓名不能为空")
    @NotBlank(message = "姓名不能位空")
    private String empName;
    @Pattern(regexp = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$",message = "身份证号不合法")
    private String empAd;
    @Length(min = 3,max = 6,message = "用户名应该为3-6位")
    private String empUsername;
    @Length(min = 4,max = 8,message = "密码应该位4-8位")
    private String empPassword;
    private String empTelNo;
    private Integer isDelete;



    private List<Role> roleList;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        Set<Authority> authoritySet = new HashSet<>();

        this.getRoleList().forEach(role -> {
            role.getAuthorityList().forEach(authority -> {
                authoritySet.add(authority);
            });
        });

        List<SimpleGrantedAuthority> simpleGrantedAuthorityList = new ArrayList<>();
        authoritySet.forEach(authority -> simpleGrantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_"+ authority.getAuthorityName())));

        return simpleGrantedAuthorityList;
    }

    @Override
    public String getPassword() {
        return this.empPassword;
    }

    @Override
    public String getUsername() {
        return this.empUsername;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.isDelete == 0 ? true : false;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empId=" + empId +
                ", empName='" + empName + '\'' +
                ", empAd='" + empAd + '\'' +
                ", empUsername='" + empUsername + '\'' +
                ", empPassword='" + empPassword + '\'' +
                ", empTelNo='" + empTelNo + '\'' +
                ", isDelete=" + isDelete +
                ", roleList=" + roleList +
                '}'+ super.toString();
    }
}
